<?php

class BusinessController extends Controller {

    public $subfolderVar = false;

    /**
     * Full path of the main uploading folder.
     * @see XUploadAction::init()
     * @var string
     * @since 0.1
     */
    public $path;

    /**
     * The resolved subfolder to upload the file to
     * @var string
     * @since 0.2
     */
    private $_subfolder;

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'rights', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    public function allowedActions() {
        return 'index, view';
    }
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function actionUploadimg($id) {

        if (isset($_SESSION['views']))
            $_SESSION['views'] = $_SESSION['views'] + 1;
        else
            $_SESSION['views'] = 1;
        $model = new XUploadForm();
        $model2 = $this->loadModel($id);
        $ct = Yii::app()->getController()->uniqueId;
        $this->path = realpath(Yii::app()->getBasePath() . "/../uploads/" . $ct . "/");

        if ($this->subfolderVar !== false) {
            $this->_subfolder = Yii::app()->request->getQuery($this->subfolderVar, $model2->id);
        } else {
            $this->_subfolder = $model2->id;
        }

        $path = $this->path . "/" . $this->_subfolder . "/";

        if (!is_dir($path)) {
            mkdir($path);
        }



        $model->file = CUploadedFile::getInstance($model2, 'file');
        $model->mime_type = $model->file->getType();
        $model->size = $model->file->getSize();
        $model->name = $model->file->getName();

        if ($model->validate()) {

            //echo    $this->actionImgcount();
            // foreach($model->file  as $file){
            $model->file->saveAs($path . $model2->id . $model->name);
            //  $file->saveAs($path.$model2->id.$model->name);
            $img = Yii::app()->simpleImage->load($path . $model2->id . $model->name);
            $img->resizeToWidth(400);

            $img->save($path . $model2->id . $model->name);
            if ($_SESSION['views'] == 1) {

                $model2->img1 = "/" . Yii::app()->getController()->uniqueId . "/" . $this->_subfolder . '/' . $model2->id . $model->name;

                $model2->save();
            } elseif ($_SESSION['views'] == 2) {

                $model2->img2 = "/" . Yii::app()->getController()->uniqueId . "/" . $this->_subfolder . '/' . $model2->id . $model->name;
                $model2->save();
            } elseif ($_SESSION['views'] == 3) {

                $model2->img3 = "/" . Yii::app()->getController()->uniqueId . "/" . $this->_subfolder . '/' . $model2->id . $model->name;
                $model2->save();
            } elseif ($_SESSION['views'] == 4) {

                $model2->img4 = "/" . Yii::app()->getController()->uniqueId . "/" . $this->_subfolder . '/' . $model2->id . $model->name;
                $model2->save();
            } elseif ($_SESSION['views'] == 5) {

                $model2->img5 = "/" . Yii::app()->getController()->uniqueId . "/" . $this->_subfolder . '/' . $model2->id . $model->name;
                $model2->save();
            }

            echo json_encode(array("name" => $model->name, "type" => $model->mime_type, "size" => $model->getReadableFileSize()));
        } else {
            echo CVarDumper::dumpAsString($model->getErrors());
            Yii::log("XUploadAction: " . CVarDumper::dumpAsString($model->getErrors()), CLogger::LEVEL_ERROR, "application.extensions.xupload.actions.XUploadAction");
            throw new CHttpException(500, "Could not upload file");
        }
        if ($_SESSION['views'] == 6)
            unset($_SESSION['views']);
    }

    public function actionSesschange($id) {
        $_SESSION['views'] = $id - 1;
        echo $_SESSION['views'];
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->layout = '//layouts/column1';
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Business;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Business'])) {
            $model->attributes = $_POST['Business'];
            if ($model->save()) {
                Yii::app()->user->setFlash('success', Yii::t('content', 'Adicionado com sucesso.'), true);

                $smessag = new SourceMessage();
                $messag = new Message();
                $smessag->category = 'content';
                $smessag->message = $model->title;
                $smessag->save();
                $smessag = new SourceMessage();
                $smessag->category = 'content';
                $smessag->message = $model->descripton;
                $smessag->save();



                if (isset($_POST['Business']['title_en'])) {
                    $lastid = $smessag->find('message="' . $_POST['Business']['title'] . '"');
                    $messag = new Message();
                    $messag->id = $lastid->id;
                    $messag->language = 'en';
                    $messag->translation = $_POST['Business']['title_en'];
                    
                    $messag->save();
                }
                if (isset($_POST['Business']['description_en'])) {
                    
                    $lastid = $smessag->find('message="' . $_POST['Business']['descripton'] . '"');
                    $messag = new Message();
                    $messag->id = $lastid->id;
                    $messag->language = 'en';
                    $messag->translation = $_POST['Business']['description_en'];
                    $messag->save();
                }
                if (isset($_POST['Business']['title_de'])) {
                    $lastid = $smessag->find('message="' . $_POST['Business']['title'] . '"');
                    $messag = new Message();
                    $messag->id = $lastid->id;
                    $messag->language = 'de';
                    $messag->translation = $_POST['Business']['title_de'];
                    $messag->save();
                }
                if (isset($_POST['Business']['description_de'])) {
                    $lastid = $smessag->find('message="' . $_POST['Business']['descripton'] . '"');
                    $messag = new Message();
                    $messag->id = $lastid->id;
                    $messag->language = 'de';
                    $messag->translation = $_POST['Business']['description_de'];
                    $messag->save();
                }
                $this->redirect(array('dashboard/index'));
            }
        }
if (isset($lastidTitleEn->trans)){
     foreach ($lastidTitleEn->trans as $key => $trans) {
         $TitleEn = $trans->translation;
     }
 }else{
     $TitleEn = "";
 }

 if (isset($lastidTitleDe->trans)){
     foreach ($lastidTitleDe->trans as $key => $trans) {
         $TitleDe = $trans->translation;
     }
 }else{
     $TitleDe = "";
 }
 
 if (isset($lastidDescDe->trans)){
     foreach ($lastidDescDe->trans as $key => $trans) {
         $DescDe = $trans->translation;
     }
 }else{
     $DescDe = "";
 }
 if (isset($lastidDescEn->trans)){
     foreach ($lastidDescEn->trans as $key => $trans) {
         $DescEn = $trans->translation;
     }
 }else{
     $DescEn = "";
 }

        $this->render('create', array(
            'model' => $model,
            'TitleEn' => $TitleEn,
            'DescEn' =>  $DescEn,
            'TitleDe' => $TitleDe,
            'DescDe' => $DescDe
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        $smessag = new SourceMessage();
        $lastidTitle = $smessag->find('message="' . $model->title . '"');
        $lastidDesc = $smessag->find('message="' . $model->descripton . '"');

        $lastidTitleEn = $smessag->with('trans')->find('message="' . $model->title . '" and trans.language="en"');
        
        $lastidDescEn = $smessag->with('trans')->find('message="' . $model->descripton . '" and trans.language="en"');
        $lastidTitleDe = $smessag->with('trans')->find('message="' . $model->title . '" and trans.language="de"');
        $lastidDescDe = $smessag->with('trans')->find('message="' . $model->descripton . '" and trans.language="de"');

      

        if (isset($_POST['Business'])) {
            $model->attributes = $_POST['Business'];
            if ($model->save()) {
                Yii::app()->user->setFlash('success', Yii::t('content', 'atualizado com sucesso.'), true);

                $smessag = $lastidTitle;

                $smessag->category = 'content';
                $smessag->message = $model->title;
                $smessag->save();
                
                $smessag = $lastidDesc;

                $smessag->category = 'content';
                $smessag->message = $model->descripton;
                $smessag->save();



                if (isset($_POST['Business']['title_en'])) {


                    if ($lastidTitleEn->trans) {
                        $messag = Message::model()->find('id=' . $lastidTitle->id .' and language="en"');
                        $messag->translation = $_POST['Business']['title_en'];
                        
                        $messag->save();
  
                    } else {
                        $messag = new Message();

                        $messag->id = $lastidTitle->id;
                        $messag->language = 'en';
                        $messag->translation = $_POST['Business']['title_en'];
                        $messag->save();
                    }
                }
                if (isset($_POST['Business']['description_en'])) {


                    if ($lastidDescEn->trans) {
                        $messag = Message::model()->find('id=' . $lastidDesc->id.' and language="en"');
                        $messag->translation = $_POST['Business']['description_en'];
                        
                        $messag->save();
                    } else {
                        $messag = new Message();
                        $messag->id = $lastidDesc->id;
                        $messag->language = 'en';
                        $messag->translation = $_POST['Business']['description_en'];
                        $messag->save();
                    }
                }
                if (isset($_POST['Business']['title_de'])) {
                    if ($lastidTitleDe->trans) {
                        $messag = Message::model()->find('id=' . $lastidTitle->id.' and language="de"');
                        $messag->translation = $_POST['Business']['title_de'];
                        $messag->save();
                    } else {
                        $messag = new Message();
                        $messag->id = $lastidTitle->id;
                        $messag->language = 'de';
                        $messag->translation = $_POST['Business']['title_de'];
                        $messag->save();
                    }
                }
                if (isset($_POST['Business']['description_de'])) {

                    if ($lastidDescDe->trans) {
                        $messag = Message::model()->find('id=' . $lastidDesc->id.' and language="de"');
                        $messag->translation = $_POST['Business']['description_de'];
                        $messag->save();
                    } else {
                        $messag = new Message();
                        $messag->id = $lastidDesc->id;
                        $messag->language = 'de';
                        $messag->translation = $_POST['Business']['description_de'];
                        $messag->save();
                    }
                }
                $this->redirect(array('dashboard/index',
                ));
            }
        }
 if (isset($lastidTitleEn->trans)){
     foreach ($lastidTitleEn->trans as $key => $trans) {
         $TitleEn = $trans->translation;
     }
 }else{
     $TitleEn = "";
 }

 if (isset($lastidTitleDe->trans)){
     foreach ($lastidTitleDe->trans as $key => $trans) {
         $TitleDe = $trans->translation;
     }
 }else{
     $TitleDe = "";
 }
 
 if (isset($lastidDescDe->trans)){
     foreach ($lastidDescDe->trans as $key => $trans) {
         $DescDe = $trans->translation;
     }
 }else{
     $DescDe = "";
 }
 if (isset($lastidDescEn->trans)){
     foreach ($lastidDescEn->trans as $key => $trans) {
         $DescEn = $trans->translation;
     }
 }else{
     $DescEn = "";
 }
        $this->render('update', array(
            'model' => $model,
            'TitleEn' => $TitleEn,
            'DescEn' =>  $DescEn,
            'TitleDe' => $TitleDe,
            'DescDe' => $DescDe
        ));
    }

    
    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
         $this->layout = '//layouts/column1';
         
        $dataProvider = Business::model()->searchFrontEnd();
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Business('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Business']))
            $model->attributes = $_GET['Business'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Business::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'business-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }


public function createSlug($title)
{

   // convert the raw title into an url friendly format here

   return $title;

}
}
